// 这是编辑
import React, { useState, useEffect } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Modal, Input, Select, Switch, message, Upload, Form, Radio, Button, InputNumber, Space } from 'antd';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
const { TextArea } = Input;
import '../css/AddClassify.less'
import { values } from 'mobx';
import { addgoods } from '../../../../api/ycl'
import { float } from 'html2canvas/dist/types/css/property-descriptors/float';
import {goodsImg} from '../../../../api/ycl'
import {api} from '../../../../api/ycl'
interface DataType {
    categoryId: number | null; //ID
    categoryName: string | undefined | null; //分类
    categoryImg: string | null,
    categoryParent: number | null | undefined, //级别
    categoryNumber: number | null, // 商品数量
    categoryStatus: string | boolean | number, //是否上架，1为上架，其余都是未上架
    categorySort: string | null, //排序
}

interface PropsType {
    isModalOpen1: boolean,
    closeModal1(): void,
    editValue: DataType | any,
    type?: string | undefined,
    coss(): void,
    dataApi(): void,
    secondar(): void,
    box: [],
}


export default function CompileClassify(props: PropsType) {
    console.log(props);
    
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>(); //图片地址 分类图标
    const [form] = Form.useForm();
    const [messageApi, contextHolder] = message.useMessage();
    const [img,setImg] = useState<string>() //存进图片地址
    useEffect(() => {
        console.log(props.editValue);
        form.setFieldsValue({
            categoryImg: api + props.editValue?.categoryImg,
            categoryName: props.editValue?.categoryName,
            categoryParent: props.editValue?.categoryParent==0?'一级':props.box,
            categoryStatus: props.editValue?.categoryStatus,
            categorySort: props.editValue?.categorySort,
        })
    }, [props])



 // 上传图片
 const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };
const handleChange = async (info:any)=>{
    console.log('%c ======>>>>>>>>', 'color:orange;', '选了图片', info)
    let { file } = info
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
    if (!isJpgOrPng) {
        return message.error('你应该上传图片类型');
    }
    //判断文件大小  是否小于2M
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        return message.error('图片太大了，请上传小于2M 的文件');
        //让图片显示出来
    }
    let myFormData = new FormData()
    myFormData.append('file',info.file)
    // 发起请求
    try{
        let res = await goodsImg(myFormData)
        if(res.code == '200'){
            console.log(res.data);
            console.log(res.data.slice(3));
            setImg(res.data.slice(3))
        }
    }catch(err){
        console.log(err);
        
    }
    //让图片显示出来
    getBase64(info.file, (url) => {
        setImageUrl(url)
    });
}



    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );


    const cancel = () => {
        props.coss()
    }
    const handleCancel = () => {
        props.coss()
    }


    type SizeType = Parameters<typeof Form>[0]['size'];
    const [componentSize, setComponentSize] = useState<SizeType | 'default'>('default');

    const onFormLayoutChange = ({ size }: { size: SizeType }) => {
        setComponentSize(size);
    };

    const layout = {
        labelCol: { span: 8 },
        wrapperCol: { span: 16 },
    };



    const onFinish = async (values: any) => {
        console.log("id",props.editValue?.categoryId);
        
        // 发起请求修改数据
        let data = ({
            categoryImg:img,
            categoryId: props.editValue?.categoryId,
            categoryName: values.categoryName,
            categoryParent: values.categoryParent=='一级'?0:values.categoryParent,
            categorySort: values.categorySort,
            categoryStatus: values.categoryStatus === true ? '1' : '4',
            description: values.description
        })

        try {
            let res = await addgoods(data)
            if (res.code == '200') {
                messageApi.open({
                    type: 'success',
                    content: '修改成功',
                });
                if (props.type == 'one') {

                    await props.dataApi()

                    props.closeModal1()
                } else if (props.type == 'two') {

                    await props.secondar()
                    props.closeModal1()
                }
            } else {
                console.log('失败');

            }
        } catch (err) {
            console.log(err);

        }
    };
    return (
        <div className='add-classify'>
            {contextHolder}
            <Modal title="编辑" open={props.isModalOpen1} centered={true} footer={null} onCancel={handleCancel}>
                <Form
                    form={form}
                    {...layout}
                    name="nest-messages"
                    onFinish={onFinish}
                    style={{ maxWidth: 600 }}
                >
                    <Form.Item name='categoryName' label="分类名称" rules={[{ required: true }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item name='categoryParent' label='上级分类'>
                        <Select
                            style={{ width: 120 }}
                            allowClear
                            options={props.box}
                        />
                    </Form.Item>
                    <Form.Item name='categorySort' label="排序">
                        <InputNumber min={1} max={100000}/>
                    </Form.Item>
                    <Form.Item name='categoryStatus' label='是否上架' valuePropName='checked' initialValue={props.editValue?.categoryStatus}>
                        <Switch/>
                    </Form.Item>
                    <Form.Item name={['upload', 'upload']} label='分类图标'>
                        <Upload
                            name="categoryImg"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                            beforeUpload={()=>false}
                            onChange={handleChange}
                        >
                            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                    </Form.Item>
                    <Form.Item name='description' label="分类描述">
                        <Input.TextArea />
                    </Form.Item>
                    <div className='button'>
                        <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
                            <Button type="primary" onClick={cancel}>
                                取消
                            </Button>
                            <Button type="primary" htmlType="submit" className='button-subnit'>
                                确定
                            </Button>
                        </Form.Item>
                    </div>
                </Form>
            </Modal>
        </div>
    )
}